package golang

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"github.com/satori/go.uuid"
	logs "github.com/sirupsen/logrus"
	"io"
	"net"
	"net/url"
	"sort"
	"strings"
	"time"
)

//如何通过付款码判断是支付宝还是微信
func checkPayChannelByAuthCode(auth_code string) string {
	if strings.HasPrefix(auth_code, "10") || strings.HasPrefix(auth_code, "11") || strings.HasPrefix(auth_code, "12") || strings.HasPrefix(auth_code, "13") || strings.HasPrefix(auth_code, "14") || strings.HasPrefix(auth_code, "15") {
		return PAY_CHANNEL_WECHAT
	} else if strings.HasPrefix(auth_code, "62") {
		return PAY_CHANNEL_CLOUD_UNION
	} else if strings.HasPrefix(auth_code, "25") || strings.HasPrefix(auth_code, "26") || strings.HasPrefix(auth_code, "27") || strings.HasPrefix(auth_code, "28") || strings.HasPrefix(auth_code, "29") || strings.HasPrefix(auth_code, "30") {
		return PAY_CHANNEL_ALIPAY
	} else {
		return "不能识别"
	}
}

func getNow() string {
	return time.Now().Format("2006-01-02 15:04:05")
}

func genTradeNo() string {
	//这里根据自身业务生成单号
	return uuid.Must(uuid.NewV4()).String()
}

func convertMap2UValue(__map map[string]interface{}) url.Values {
	ret := url.Values{}
	for k, v := range __map {
		ret[k] = []string{fmt.Sprintf("%v", v)}
	}
	return ret
}

func doSign(__map map[string]interface{}, APP_SECRET string) string {
	sorted_keys := make([]string, 0)
	for k, _ := range __map {
		sorted_keys = append(sorted_keys, k)
	}
	sort.Strings(sorted_keys)
	//对key=value的键值对用&连接起来，略过空值
	var signStrings string
	for _, k := range sorted_keys {
		value := fmt.Sprintf("%v", __map[k])
		if value != "" {
			signStrings = signStrings + k + "=" + value + "&"
		}
	}
	signStrings += "APP_SECRET=" + APP_SECRET
	logs.Error("待签名数据:", signStrings)
	ret := __md5(signStrings)
	logs.Error("签名结果 :", ret)
	return ret
}

func __md5(data string) string {
	m := md5.New()
	io.WriteString(m, data)
	x := hex.EncodeToString(m.Sum(nil))
	return strings.ToUpper(x)
}

func getLocalIp() string {
	if addrs, err := net.InterfaceAddrs(); err != nil {
		return "127.0.0.1"
	} else {
		for _, a := range addrs {
			if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
				if ipnet.IP.To4() != nil {
					return ipnet.IP.String()
				}
			}
		}
	}
	return "127.0.0.1"
}
